package com.decent.common.config.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * @author zhangzx@decent.cn
 * @date 2020/12/26
 */
public class TwoDecimalPlacesSerializer extends JsonSerializer<BigDecimal> {
    /**
     * 格式化BigDecimal为四舍五入后的两位小数
     * 使用 @JsonSerialize(using = TwoDecimalPlacesSerializer.class)
     *
     * @param value       Value to serialize; can <b>not</b> be null.
     * @param gen         Generator used to output resulting Json content
     * @param serializers Provider that can be used to get serializers for
     */
    @Override
    public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value != null) {
            BigDecimal number = value.setScale(2, RoundingMode.HALF_UP);
            gen.writeNumber(number);
        } else {
            gen.writeNumber((BigDecimal) null);
        }
    }
}
